//
// GPSMapEdit
// (c) Konstantin Galichsky (kg@geopainting.com), 2005-2007
//
// File helpers.
//

# include "StdAfx.h"
# include "File.h"

void GetLocalFileName (const TCHAR * _strRelativeName, TCHAR _strAbsoluteFileName [MAX_PATH]) {
	::GetModuleFileName (NULL, _strAbsoluteFileName, MAX_PATH);
	TCHAR * p = ::_tcsrchr (_strAbsoluteFileName, '\\');
	if (p == NULL)
		 p = _strAbsoluteFileName;
	else
		++ p;
	::_tcscpy (p, _strRelativeName);
}

bool DoesFileExist (const TCHAR * _strFileName) {
	return ::GetFileAttributes (_strFileName) != 0xFFFFFFFF;
}

size_t CountFiles (const TCHAR * _strFilter) {
	WIN32_FIND_DATA fd;
	const HANDLE hFind = ::FindFirstFile (_strFilter, & fd);
	if (hFind == INVALID_HANDLE_VALUE)
		return 0;

	size_t cFiles = 0;
	do {
		if (
			::_tcscmp (fd.cFileName, ".")  == 0 ||
			::_tcscmp (fd.cFileName, "..") == 0
		)
			continue;
		++ cFiles;
	} while (::FindNextFile (hFind, & fd));

	return cFiles;
}

void CreateUniqueFileName (const TCHAR * _strFileName, const TCHAR * _strExt, TCHAR _strUniqueName [MAX_PATH]) {
	const char * const pDot = ::strrchr (_strFileName, '.');
	const size_t cFileNameLen = pDot ? pDot - _strFileName : ::strlen (_strFileName);

	::strncpy (_strUniqueName, _strFileName, cFileNameLen);
	::sprintf (_strUniqueName + cFileNameLen, ".%s", _strExt);
	if (! DoesFileExist (_strUniqueName))
		return;

	size_t cOrdinal = 0;
	do {
		++ cOrdinal;
		::sprintf (_strUniqueName + cFileNameLen, "(%d).%s", cOrdinal, _strExt);
	} while (DoesFileExist (_strUniqueName));
}